//配置aixos统一路径
import axios from 'axios'
import { getToken, removeToken } from './token'
import { history } from './history'
const http = axios.create({
  baseURL: 'http://geek.itheima.net/v1_0/',
  timeout: 5000,
})

//请求拦截器，为非登录接口统一添加token
http.interceptors.request.use(config => {
  if (config.url !== 'authorizations') {
    config.headers.Authorization = `Bearer ${getToken()}`
  }
  return config
})
// 响应拦截器,处理token失效问题
http.interceptors.response.use(
  response => {
    return response
  },
  error => {
    console.dir(error)
    if (error.response.status === 401) {
      //移除token
      removeToken()
      //token失效，跳转登录页面
      history.push('/login')
    }
    //此处相当于return Promise.resolve(error)
    // return error
    // 返回失败的结果
    return Promise.reject(error)
  }
)
export { http }
